import Storage from './storage';
import {Platform, DeviceEventEmitter} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {navigate} from '@/router/RootNavigation';

let queryString = require('query-string');

function jumpurl(url, params) {
  AsyncStorage.clear().then(() => {
    navigate(url, params);
  });
  return null;
}

const baseUrl = global.path ?? 'http://192.168.40.146:8898'; //  'http://tasks-dev.nangaoyun.com/api';

const os = Platform.OS;

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    let error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
}

function parseJSON(response) {
  let res = response.json();
  return res.then(data => {
    switch (data.code) {
      case -1:
        jumpurl('Login');
        break;
      case '0007':
        // jumpurl("Errors", { code: "0007" });
        break;
      case 0:
        //成功
        break;
      default:
        DeviceEventEmitter.emit('toast', {
          message: data.msg,
          type: 'warning',
        });
        // OneToast(data.msg, "rgba(254,162,0,0.6)")
        break;
    }
    return data;
  });
}

async function get(url, params) {
  if (params) {
    url += `?${queryString.stringify(params)}`;
  }
  try {
    let headers = new Headers();
    let token = await Storage.get('token');
    if (token) {
      headers.append('token', token);
      headers.append('UserAgent', os);
      headers.append('Connection', 'close');
    }
    return fetch(baseUrl + url, {
      headers: headers,
    })
      .then(checkStatus)
      .then(parseJSON)
      .catch(error => {});
  } catch (e) {}
}

async function post(url, body) {
  let token = await Storage.get('token'),
    TOKEN = '';
  if (token) {
    TOKEN = token;
  }
  let fetchOptions = {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=utf-8',
      token: TOKEN,
      Connection: 'close',
      UserAgent: os,
    },
    body: JSON.stringify(body),
  };
  return fetch(baseUrl + url, fetchOptions)
    .then(checkStatus)
    .then(parseJSON)
    .catch(error => {});
}

async function del(url, params) {
  if (params) {
    url += `?${queryString.stringify(params)}`;
  }
  let token = await Storage.get('token');
  let fetchOptions = {
    method: 'DELETE',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Connection: 'close',
      token: token ? token : '',
      UserAgent: os,
    },
  };
  return fetch(baseUrl + url, fetchOptions)
    .then(checkStatus)
    .then(parseJSON);
}

async function update(url, body) {
  let token = await Storage.get('token');
  let fetchOptions = {
    method: 'PUT',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Connection: 'close',
      token: token ? token : '',
      UserAgent: os,
    },
    body: JSON.stringify(body),
  };
  return fetch(baseUrl + url, fetchOptions)
    .then(checkStatus)
    .then(parseJSON);
}

async function uploadFile(url, params) {
  let token = await Storage.get('token'),
    TOKEN = '';
  if (token) {
    TOKEN = token;
  }
  const fetchOptions = {
    method: 'POST',
    headers: {
      token: TOKEN,
      //UserAgent: os,
      'Content-Type': 'multipart/form-data',
    },
    body: params,
  };
  return fetch(baseUrl + url, fetchOptions)
    .then(checkStatus)
    .then(parseJSON);
}

export {get, post, del, update, uploadFile};
